<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
require_once 'WXBizDataCrypt.class.php';

class Member extends Model
{
    protected $appid = "wxe771a17a54396bb5";
    protected $secret = "3e181caf5cf57866910ed4ce08c73891";
    protected $table = 'user';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $fillable=[];


    /*
  *是否有记录登录信息
  */
    public function isLogin($unionid)
    {
        return Member::where('unionid', $unionid)->first();
    }

    //获取用户的openId和session_key
    public function login()
    {
        $code = $_GET["code"];
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->secret&js_code=$code&grant_type=authorization_code";
        if (false !== $apiData = json_decode(file_get_contents($URL), true)) {
            return $apiData;
        }
        return false;
    }

//获取用户信息
    public function getUserInfo()
    {
        //调用获取用户的openId和session_key方法
        if ((false !== $apiData = $this->login()) && !isset($apiData['errcode'])) {
            $sessionKey = $apiData['session_key'];
            $userifo = new \WXBizDataCrypt($this->appid, $sessionKey);
            $encryptedData = $_GET["encryptedData"];//微信小程序传过来的
            $iv = $_GET["iv"];//微信小程序传过来的
            $errCode = $userifo->decryptData($encryptedData, $iv, $data);
            if ($errCode == 0) {
                return json_decode($data, true);
            } else {
                return false;
            }
        }
        return false;
    }


    //如果用户不存在去执行这里注册
    public function createUser($userInfo)
    {

        DB::beginTransaction(); //事务
        try {
            $member = new Member;
            $member->open_id = $userInfo['openId'];
            $member->unionid = $userInfo['unionId'];
            $member->username = $userInfo['nickName'];
            $member->gender = $userInfo['gender'];
            $member->head_ico = $userInfo['avatarUrl'];
            $member->city = $userInfo['city'];
            $member->province = $userInfo['province'];
            $member->api_token = str_random(60);
            $member->ip = $this->real_ip();
            $member->created_at = time();
            $member->save();

        //firstOrCreate判断用如果openid不存在则写入新数据//这里的检测要全部加入模型里的白名单
        $user_wallet = Wallet::firstOrCreate(
            [
                'openid' => $member->open_id,
            ],

            [
                    'uid'=>$member->id,
                    'openid'=>$userInfo['openId'],
            ]);

            if($member&&$user_wallet){
                DB::commit();
                //echo 'success';
                $user_wallet = Wallet::where('openid',$member->open_id)->first();
                if($user_wallet->wallet == null)
                {
                    $wallet = 0;
                }
                return ['money'=>number_format($user_wallet->money ,2, '.', '')];

            }
        } catch (\Exception $e) {
            DB::rollBack();
            echo $e;
            $mylog = new MyLog;
            $mylog->setLog('获取用户信息数据异常:' . $e, $logPath = 'userLogin');
        }


    }


    /**
     * 获得用户的真实IP地址
     */
    public function real_ip()
    {
        static $realip = null;

        if ($realip !== null) {
            return $realip;
        }

        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach ($arr as $ip) {
                    $ip = trim($ip);

                    if ($ip != 'unknown') {
                        $realip = $ip;

                        break;
                    }
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realip = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realip = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }

        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

        return $realip;
    }

    /**
     * $conditions 返回会员信息
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public static function listMember($conditions,$type='id') {
        $memberInfoList = [];
        if ($type == 'id') {
            $fields = ["id","username","head_ico"];
            foreach (self::whereIn("id",$conditions)->cursor() as $member) {
                $memberInfoList[$member->id] = ["username"=>$member->username,"head_ico" => $member->head_ico];
            }
            return $memberInfoList;
        }
        if ($type == 'openid') {
            $fields = ["open_id","username","head_ico"];
            foreach (self::whereIn("open_id",$conditions)->cursor() as $member) {
                $memberInfoList[$member->open_id] = ["username"=>$member->username,"head_ico" => $member->head_ico];
            }
            return $memberInfoList;
        }
    }

}
